import { View, Text } from '@tarojs/components';
import { toClassName } from '@/utils';
import styles from './style.scss';

type Props = {
  value?: any;
  onChange?: (value: Props['value']) => void;
  options?: Array<{ value: any; text: any }>;
  readOnly?: boolean;
  multiple?: boolean;
};

export default (props: Props) => {
  const { options, value, onChange, readOnly, multiple } = props;
  return (
    <View className={styles.container}>
      {options?.map((item) => (
        <Text
          className={toClassName([
            styles.item,
            (Array.isArray(value)
              ? value.includes(item.value)
              : value === item.value) && styles.active,
          ])}
          key={item.value}
          onClick={() => {
            if (readOnly) return;
            if (multiple) {
              if (value?.includes?.(item.value)) {
                onChange?.(value.filter((it) => it !== item.value));
              } else {
                onChange?.([...(value || []), item.value]);
              }
            } else {
              onChange?.(item.value);
            }
          }}
        >
          {item.text}
        </Text>
      ))}
    </View>
  );
};
